import java.util.List;

public class Solution148 {
    /**
     * 在 O(n log n) 时间复杂度和常数级空间复杂度下，对链表进行排序。
     */

    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode mid = findMid(head);
        ListNode rightHead = mid.next;
        mid.next = null;

        ListNode left = sortList(head);
        ListNode right = sortList(rightHead);

        return merge(left, right);
    }

    private ListNode merge(ListNode left, ListNode right) {
        ListNode head = new ListNode(0);
        ListNode cur = head;

        while (left!= null && right !=null){
            if (left.val < right.val){
                cur.next = left;
                left = left.next;
            }else {
                cur.next = right;
                right = right.next;
            }
            cur = cur.next;
        }
        cur.next = left != null? left : right;
        return head.next;
    }

    public ListNode findMid(ListNode node){
        if (node == null || node.next == null){
            return node;
        }
        ListNode s = node;
        ListNode f = node.next.next;
        while (f != null && f.next !=null){
            s = s.next;
            f = f.next.next;
        }
        return s;
    }
}
